#include "stdheader.h"

/////////////////////////////////////////////////////////

CGame::CGame()
{
	m_bRunning = false;
	m_eGameState = EGameState_None;
	m_ePendingState = EGameState_None;
	m_tGameFont.loadFromFile("Resources/Fonts/Cihuy.ttf");
}

/////////////////////////////////////////////////////////

CGame::~CGame()
{

}

/////////////////////////////////////////////////////////

bool CGame::Initialise()
{
	m_bRunning = true;
	m_tClock.restart();
	m_eGameState = EGameState_Splash;
	m_iActiveChar = 0;
	
	m_pActiveScreen = new CSplashScreen();
	m_pActiveScreen->LayoutScreen();

	return true;
}

/////////////////////////////////////////////////////////

void CGame::Run()
{
	if (m_tClock.getElapsedTime().asSeconds() >= FRAME_RATE)
	{
		ProcessInput();
		Process(m_tClock.getElapsedTime().asSeconds());
		Render();

		m_tClock.restart();
	}
}

/////////////////////////////////////////////////////////

void CGame::Render()
{
	m_pWin->clear();

	m_pActiveScreen->Render(m_pWin);

	m_pWin->display();
}

/////////////////////////////////////////////////////////

void CGame::Process(float fTimeDelta)
{
	if (m_ePendingState > 0 && m_pActiveScreen->IsFading() == false)
	{
		ChangeState();
	}

	m_pActiveScreen->Process(fTimeDelta);
}

/////////////////////////////////////////////////////////

void CGame::ProcessInput()
{
	sf::Event tEvent;
	while (m_pWin->pollEvent(tEvent))
	{
		// Generic event handling
		switch(tEvent.type)
		{
		case sf::Event::Closed:
			m_bRunning = false;
			break;
		default:
			m_pActiveScreen->ProcessInput(tEvent);
			break;
		}
	}
}

/////////////////////////////////////////////////////////

void CGame::Cleanup()
{

	m_pWin->close();
}

/////////////////////////////////////////////////////////

void CGame::ChangeState()
{ 
	m_eGameState = m_ePendingState; 
	m_ePendingState = EGameState_None; 

	delete m_pActiveScreen;

	switch (m_eGameState)
	{
	case EGameState_MainMenu:
		m_pActiveScreen = new CMenuScreen();
		break;
	case EGameState_InGame:
		m_pActiveScreen = new CInGameScreen();
		break;
	}

	m_pActiveScreen->LayoutScreen();
}

/////////////////////////////////////////////////////////

CGame* CGame::Instance()
{
	static CGame instance;

	return &instance;
}